import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import config from './config';
import { APP_GUARD } from '@nestjs/core';
import { SystemModule } from './modules/system/system.module';
import { LoggerMiddleware } from './middleware/logger.middleware';
import { BillingModule } from './modules/billing/billing.module';
import { AuthGuard } from './guards/auth.guard';
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';

@Module({
  imports: [
    // 配置模块
    ConfigModule.forRoot({
      cache: true,
      load: [config],
      isGlobal: true,
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        type: 'mysql',
        host: config.get('mysql.host'),
        port: config.get('mysql.port'),
        username: config.get('mysql.username'),
        password: config.get('mysql.password'),
        database: config.get('mysql.database'),
        synchronize: config.get('mysql.synchronize'), // synchronize: true 可确保每次运行应用程序时实体都将与数据库同步
        logging: config.get('mysql.logging'),
        timezone: config.get('mysql.timezone'),
        // entities: [`${__dirname}/**/*.entity{.ts,.js}`],
        autoLoadEntities: true,
        namingStrategy: new SnakeNamingStrategy(), // 关联字段下划线方式
      }),
    }),
    SystemModule, // 系统模块
    BillingModule, // 账单模块
  ],
  providers: [
    // 路由权限标识守卫
    {
      provide: APP_GUARD,
      useClass: AuthGuard,
    },
  ],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    // 日志配置
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}
